package main

import (
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func LoggerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		raw := c.Request.URL.RawQuery

		// 请求处理前的操作
		log.Printf("Start handling request: %s?%s", path, raw)

		// 继续处理请求链中的其他处理器和中间件
		c.Next()

		// 请求处理后的操作
		end := time.Now()
		latency := end.Sub(start)
		statusCode := c.Writer.Status()
		clientIP := c.ClientIP()

		log.Printf("| %3d | %13v | %15s | %40s |\n",
			statusCode, latency, clientIP, path+"?"+raw)
	}
}

func RateLimitMiddleware(limit int) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 这里只是一个简单的示例，实际应用中应该实现更复杂的限流逻辑
		time.Sleep(time.Duration(limit) * time.Millisecond)
		c.Next()
	}
}

func main() {
	r := gin.Default()

	// 添加全局中间件
	r.Use(LoggerMiddleware())

	// 创建一个没有额外中间件的公共路由分组
	public := r.Group("/public")
	{
		public.GET("/ping", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{"message": "pong"})
		})
	}

	// 创建一个有速率限制的分组
	limit := r.Group("/limited", RateLimitMiddleware(100))
	{
		limit.GET("/slow", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{"message": "This is a rate-limited endpoint"})
		})
	}

	r.Run(":8080")
}
